package service

import (
	"fly/models"
	"fly/resp"
	"github.com/beego/beego/v2/client/orm"
	"net/url"
)

type LifetimeRecordService struct {
	BaseService
	AircraftService AircraftService
}

func (c *LifetimeRecordService) GetPaginateData(params url.Values) ([]*models.LifetimeRecord, Pagination) {
	c.WhereField = append(c.WhereField, new(models.LifetimeRecord).WhereField()...)
	var data []*models.LifetimeRecord
	var aircraft *resp.SimpleAircraft
	if aircraftCode := params.Get("code"); len(aircraftCode) > 0 {
		// 若传入了飞机code，就强制检查飞机
		aircraft, _ = c.AircraftService.GetSimpleAircraftByCode(aircraftCode)
		if aircraft == nil {
			return data, c.Pagination
		}
	}
	o := orm.NewOrm().QueryTable(new(models.LifetimeRecord))
	_, err := c.PaginateAndScopeWhere(o, params, func(cond *orm.Condition) *orm.Condition {
		if aircraftCode := params.Get("code"); len(aircraftCode) > 0 {
			// 指定飞机
			if aircraft != nil {
				cond = cond.And("aircraft_id", aircraft.Id)
			}
		}
		return cond
	}).All(&data)
	if err != nil {
		return nil, c.Pagination
	}
	return data, c.Pagination
}

func (c *LifetimeRecordService) GetRecordCount(aircraftId, componentId int64) int {
	qs := orm.NewOrm().QueryTable(new(models.LifetimeRecord))
	o := qs.Filter("aircraft_id", aircraftId)
	if componentId > 0 {
		o = qs.Filter("component_id", componentId)
	}
	count, _ := o.Count()
	return int(count)
}

// GetRecordByTaskId 根据任务取添加的有寿记录
func (c *LifetimeRecordService) GetRecordByTaskId(taskId int64) []*models.LifetimeRecord {
	var list []*models.LifetimeRecord
	qs := orm.NewOrm().QueryTable(new(models.LifetimeRecord)).Filter("task_id", taskId)
	_, err := qs.All(&list)
	if err != nil {
		return nil
	}
	return list
}
